<?php

namespace app\api\controller;

use app\BaseController;
use app\service\apixcxService;
use app\service\WxTplService;
use think\facade\Db;

class Stranger extends BaseController
{

    public function add(){
        $qrcode_id = request()->param("device_id");
        $deviceInfo=Db::table("device")->where("qrcode_id",$qrcode_id)->find();
        if(empty($deviceInfo)){
            parent::sendOutput("设备信息错误",500);
        }
        $code=request()->param("auth_code");
        $api = new apixcxService();
        //获取当前用户支付宝ID
        $oauthtoken = $api->xcxoauthToken($code);
        if(property_exists($oauthtoken,'sub_msg')){
            parent::sendOutput($oauthtoken->sub_msg,500);
            //return json(['msg' => $oauthtoken->sub_msg,'code'=>"500"]);
        }
        $user_id = $oauthtoken->open_id;
        $applyInfo=Db::table("stranger_apply")
            ->where("user_id",$user_id)
            ->where("qrcode_id", $qrcode_id)
            ->where("status",1)
            ->find();
        if(!empty($applyInfo)){
            parent::sendOutput("请勿重复提交记录",500);
        }
        $str=request()->param("str");
        $result=openssl_decrypt(base64_decode($str), 'AES-128-CBC', base64_decode(env("APP.AES_KEEY")),OPENSSL_RAW_DATA);
        $result= json_decode($result, true);
        if($result["code"]!="10000"){
            parent::sendOutput("用户手机号获取失败",500);
        }
        $nick_name=request()->param("nickName");
        $name=request()->param("name");
        $avatar=request()->param("image");
        $mobile=$result["mobile"];

        $add["user_id"]=$user_id;
        $add["community_id"]=$deviceInfo["community_id"];
        $add["community_name"]=$deviceInfo["community_name"];
        $add["create_time"]=date("Y-m-d H:i;s");
        $add["mobile"]=$mobile;
        $add["nick_name"]=$nick_name;
        $add["name"]=$name;
        $add["avatar"]= $avatar;
        $add["qrcode_id"]=$qrcode_id ;
        $add["device_id"]=$deviceInfo["id"] ;
        $add["device_name"]=$deviceInfo["lockname"];

        //查询用户是否已经有记录

        $res=Db::table("stranger_apply")->insertGetId($add);
        if($res){
            $staffList=Db::table("staff")
                ->where("community_id",$deviceInfo["community_id"])
                //->where("opneid")
                ->where("status","on")
                ->select();
            $add["id"]=$res;
            foreach($staffList as $staffInfo){

                (new WxTplService())->sendVerifyMsg($add,$staffInfo);

            }
            parent::sendOutput("添加成功");
        }else{
            parent::sendOutput("添加失败",500);
        }
    }
}